package xyz.ieden.freemarker.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.ieden.freemarker.entity.User;
import xyz.ieden.freemarker.servlet.IUserServlet;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Gavin on 2017.09.09.
 */
//@RestController
//@RequestMapping("user")
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired(required = false)
    private IUserServlet userServlet;

    @DeleteMapping("{userId}")
    public void deleteUserById(@PathVariable("userId")Long userId, HttpServletRequest request) {
        LOGGER.info("用户请求 ip：" + request.getRemoteAddr());
        userServlet.deleteUserById(userId);
    }

    @PutMapping("")
    public User updateUser(User user, HttpServletRequest request) {
        LOGGER.info("用户请求 ip：" + request.getRemoteAddr());
        User qryUser = userServlet.updateUser(user);
        LOGGER.info("新创建的用户的 id：{}", qryUser.toString());
        return qryUser;
    }

    @PostMapping("")
    public User createUser(User user, HttpServletRequest request) {
        LOGGER.info("用户请求 ip：" + request.getRemoteAddr());
        User saveUser = userServlet.saveUser(user);
        LOGGER.info("新创建的用户信息：{}", saveUser.toString());
        return saveUser;
    }

    @GetMapping("{userId}")
    public User getUserById(@PathVariable("userId")Long userId, HttpServletRequest request) {
        LOGGER.info("用户请求 ip：" + request.getRemoteAddr());
        User user = userServlet.getUserById(userId);
        LOGGER.info("用户信息：{}", user.toString());
        return user;
    }

    @GetMapping(value = "")
    public List<User> getAllUser(HttpServletRequest request) {
        LOGGER.info("用户请求 ip：" + request.getRemoteAddr());
        List<User> userList = userServlet.getAllUser();
        LOGGER.info("用户数量：{}", userList.size());
        return userList;
    }
}
